const {ipcRenderer, webFrame} = require('electron')
const fs = require('fs')

webFrame.setZoomLevel(1)
webFrame.setVisualZoomLevelLimits(1, 1)
webFrame.setZoomFactor(1)

function showImage(image, finishCallback) {
    let img = new Image();
    img.src = image;
    img.onload = function () {
        let width = img.width
        let height = img.height
        let scale = width / (height * 1.0)
        let point = window.focusany.getCursorScreenPoint();
        let display = window.focusany.getDisplayNearestPoint(point)
        if (display) {
            width = width / display.scaleFactor
            height = height / display.scaleFactor
            width = Math.min(width, display.size.width * 0.8);
            height = width / scale;
            height = Math.min(height, display.size.height * 0.8);
            width = height * scale;
        }
        const info = window.focusany.getPluginInfo()
        let main = info.main
        if (!main.startsWith('http://')) {
            if(!main.startsWith('file://')) {
                main = `file://${main}`
            }
        }
        let win = window.focusany.createBrowserWindow(main, {
            name: 'ImagePin',
            title: 'ImagePin',
            width: parseInt(width),
            height: parseInt(height),
            useContentSize: true,
            center: true,
            skipTaskbar: true,
            minimizable: false,
            maximizable: false,
            fullscreenable: false,
            transparent: false,
            backgroundColor: '#00000000',
            frame: false,
            alwaysOnTop: true,
            hasShadow: true,
            webPreferences: {
                preload: 'show.cjs',
                devTools: true,
            }
        }, () => {
            win.setAlwaysOnTop(true);
            if (window.focusany.getPluginEnv() === 'dev') {
                win.webContents.openDevTools({
                    mode: 'detach'
                });
            }
            ipcRenderer.send('SendTo', win.webContents.id, 'init', {
                image: image
            })
            ipcRenderer.on('resize', (event, fromWinId, changed, proportion) => {
                let nowBounds = win.getBounds()
                let widthChanged = nowBounds.width + changed
                win.setSize(Math.ceil(widthChanged), Math.ceil(widthChanged * proportion));
            });
            ipcRenderer.on('moveBounds', (event, fromWinId, x, y, width, height) => {
                let bound = win.getBounds();
                let newBounds = {
                    x: parseInt(bound.x + x),
                    y: parseInt(bound.y + y),
                    width: parseInt(width || bound.width),
                    height: parseInt(height || bound.height)
                }
                win.setBounds(newBounds);
            });
            ipcRenderer.on('modifyOpacity', (event, fromWinId, opacity) => {
                win.setOpacity(opacity);
            })
            ipcRenderer.on('triggerPin', (event, fromWinId) => {
                let isPin = win.isAlwaysOnTop();
                win.setAlwaysOnTop(!isPin);
                ipcRenderer.send('SendTo', win.webContents.id, 'pinChange', !isPin);
            })
            ipcRenderer.on('copyImage', (event, fromWinId) => {
                win.capturePage().then(img => {
                    const base64 = `data:image/png;base64,${window.focusany.util.bufferToBase64(img.toPNG())}`
                    // console.log('copyImage', base64)
                    window.focusany.copyImage(base64)
                    window.focusany.showNotification('图片已经拷贝至剪切板')
                    ipcRenderer.send('SendTo', win.webContents.id, 'reduction');
                })
            });
            ipcRenderer.on('saveImage', (event, fromWinId) => {
                win.capturePage().then(img => {
                    let defaultPath = window.focusany.getPath('downloads') + "/ImagePin_" + window.focusany.util.datetimeString() + ".png"
                    let savePath = window.focusany.showSaveDialog({
                        title: '保存图片', defaultPath: defaultPath, buttonLabel: '保存'
                    })
                    if (savePath) {
                        fs.writeFileSync(savePath, img.toPNG());
                        window.focusany.showNotification("保存成功")
                    }
                    ipcRenderer.send('SendTo', win.webContents.id, 'reduction');
                })
            });
            win.on('will-resize', (event, newBounds) => {
                event.preventDefault();
                ipcRenderer.send('SendTo', win.webContents.id, 'will-resize', newBounds);
            });
            win.on('focus', () => {
                ipcRenderer.send('SendTo', win.webContents.id, 'focus');
            })
            win.on('blur', () => {
                ipcRenderer.send('SendTo', win.webContents.id, 'blur');
            })
        });
        win.on('closed', () => {
            setTimeout(finishCallback, 1000)
        });
    }
}

function showAll(images, finishCallback) {
    let imageCount = images.length
    for (const image of images) {
        showImage(image, () => {
            imageCount--
            if (imageCount === 0) {
                finishCallback()
            }
        })
    }
}

window.exports = {
    "code": {
        "default": async (data) => {
            console.log('default', data)
            console.log('keywords', window)
            // console.log('clipboardText', window.focusany.getClipboardText())
            // console.log('currentImage', window.focusany.getClipboardImage())
            // console.log('currentFiles', window.focusany.getClipboardFiles())
            if (!data.actionMatch) {
                return
            }
            const getText = () => {
                const query = window.focusany.getQuery(data.requestId)
                let text = query.clipboardText
                if (!text) {
                    text = query.keywords
                }
                return text
            }
            const images = []
            if ('image' === data.actionMatch.name) {
                images.push(window.focusany.getClipboardImage())
            } else if ('svg' === data.actionMatch.name) {
                images.push(`data:image/svg+xml;base64,${window.focusany.util.base64Encode(getText())}`)
            } else if ('base64' === data.actionMatch.name) {
                images.push(getText())
            } else if ('file' === data.actionMatch.name) {
                let files = window.focusany.getClipboardFiles()
                const mineMap = {
                    "gif": "image/gif",
                    "jpeg": "image/jpeg",
                    "jpg": "image/jpeg",
                    "png": "image/png",
                    "svg": "image/svg+xml",
                    "webp": "image/webp",
                    "ico": "image/x-icon"
                }
                for (const f of files) {
                    if (!f.isFile || !(f.fileExt in mineMap)) {
                        continue
                    }
                    const data = fs.readFileSync(f.path)
                    images.push(`data:${mineMap[f.fileExt]};base64,${data.toString('base64')}`)
                }
            }
            if (images.length > 0) {
                return new Promise((resolve, reject) => {
                    showAll(images, resolve)
                })
            } else {
                window.focusany.showNotification('没有找到图片')
            }
        }
    }
}
